package com.hanson.api;

import com.alibaba.fastjson.JSONObject;
import com.hanson.common.bean.ResultMessage;
import com.hanson.entity.GoodsBean;
import com.hanson.entity.SeckillGoodsBean;
import com.hanson.service.GoodsCommentService;
import com.hanson.service.GoodsService;
import com.hanson.service.SeckillGoodsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Api(tags = "秒杀管理")
@RestController
@RequestMapping("/api/skillGoods")
public class SkillGoodsGoodsApiController {
    @Autowired
    private SeckillGoodsService seckillGoodsService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsCommentService goodsCommentService;

    @ApiOperation(value = "查询秒杀商品")
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public ResultMessage query() throws Exception {
        ResultMessage resultMessage = new ResultMessage();
        ModelMap modelMap = new ModelMap();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", seckillGoodsService.getSkillTimeData(modelMap));
        jsonObject.put("currentIndex", modelMap.get("currentIndex"));
        jsonObject.put("seconds", String.valueOf(seckillGoodsService.getSurplusSecond()));
        resultMessage.setData(jsonObject);
        return resultMessage;
    }

    @ApiOperation(value = "秒杀商品详情")
    @RequestMapping(value = "/skillDetail/{id}", method = RequestMethod.GET)
    public ResultMessage skillDetail(@PathVariable("id") String id, HttpServletRequest request) throws WxErrorException {
        SeckillGoodsBean seckillGoodsBean = seckillGoodsService.selectById(Integer.parseInt(id));
        if (null != seckillGoodsBean) {
            seckillGoodsService.fillAttrs(seckillGoodsBean);
        }
        GoodsBean goodsBean = goodsService.detail(seckillGoodsBean.getGoodsId());
        ModelMap modelMap = new ModelMap();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("killData", seckillGoodsBean);
        jsonObject.put("data", goodsBean);
        jsonObject.put("comment", goodsCommentService.selectByGoodsId(goodsBean.getId(), 0, modelMap));
        jsonObject.put("countData", modelMap.get("countData"));
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setData(jsonObject);
        return resultMessage;
    }
}
